#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
# 

"""
File: unit2.py
Author: zhangyang(zhangyang40@baidu.com)
Date: 2018/2/2 0002 14:26
"""
import warnings

warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import logging

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
from collections import defaultdict

from gensim import corpora

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
             "The EPS user interface management system",
             "System and human system engineering testing of EPS",
             "Relation of user perceived response time to error measurement",
             "The generation of random binary unordered trees",
             "The intersection graph of paths in trees",
             "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents]
frequency = defaultdict(int)
for text in texts:
    for token in text:
        frequency[token] += 1
texts = [[token for token in text if frequency[token] > 1] for text in texts]
# pprint(texts)
dictionary = corpora.Dictionary(texts)
dictionary.save('data/deerwester.dict')
print(dictionary)
print(dictionary.token2id)
new_doc = "Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.lower().split())
# print(new_vec)
corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('data/deerwester.mm', corpus)
print(corpus)


class MyCorpus(object):
    def __iter__(self):
        for line in open('data/mycorpus.txt'):
            # assume there's one document per line, tokens separated by whitespace
            yield dictionary.doc2bow(line.lower().split())


corpus_memory_friendly = MyCorpus()
for vector in corpus_memory_friendly:
    print(vector)

dictionary = corpora.Dictionary(line.lower().split() for line in open('data/mycorpus.txt'))
stop_ids = [dictionary.token2id[stopword] for stopword in stoplist if stopword in dictionary.token2id]
once_ids = [tokenid for tokenid, docfreq in dictionary.dfs.items() if docfreq == 1]
dictionary.filter_tokens(stop_ids + once_ids)  # 删除停用词和仅出现一次的词
dictionary.compactify()  # 消除id序列在删除词后产生的不连续的缺口
print(dictionary)
corpus = [[(1, 0.5)], []]
corpora.MmCorpus.serialize('data/corpus.mm', corpus)
corpora.SvmLightCorpus.serialize('data/corpus.svmlight', corpus)
corpora.BleiCorpus.serialize('data/corpus.lda-c', corpus)
corpora.LowCorpus.serialize('data/corpus.low', corpus)
corpus = corpora.MmCorpus('data/corpus.mm')
print(corpus)
print(list(corpus))
for doc in corpus:
    print(doc)
# corpus = gensim.matutils.Dense2Corpus(numpy_matrix)
# numpy_matrix = gensim.matutils.corpus2dense(corpus, num_terms=number_of_corpus_features)
# corpus = gensim.matutils.Sparse2Corpus(scipy_sparse_matrix)
# scipy_csc_matrix = gensim.matutils.corpus2csc(corpus)
